package com.coding.service.impl;


import com.coding.dto.RestBean;
import com.coding.mapper.UserMapper;
import com.coding.pojo.Users;
import com.coding.service.UserService;
import com.coding.util.JWTUtils;
import com.coding.util.ResponseDTO;
import com.coding.vo.LoginVo;
import io.jsonwebtoken.ClaimsBuilder;
import io.jsonwebtoken.Jwts;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 手机密码登录
     *
     * @param vo
     * @return
     */
    @Override
    public RestBean<Users> login(LoginVo vo) {
        System.out.println("*******loginimpl*******" + vo);
        Users Phone = userMapper.selectByPhone(vo.getPhoneNumber());
        if (Phone != null) {
            Users login = userMapper.login(vo.getPhoneNumber(), vo.getPassWord());
            if (login != null) {
                ClaimsBuilder claims = Jwts.claims();
                claims.add("PhoneNumber", login.getPhoneNumber());
                String token = JWTUtils.getToken(claims.build());
                System.out.println("生成的token是:" + token);
                redisTemplate.opsForValue().set(token, login);
                redisTemplate.expire("token", 10000, TimeUnit.MINUTES);
                login.setToken(token);

                return RestBean.success("登录成功", login);
            }
            return RestBean.failure(400,"登录失败");
        } else {
            return RestBean.failure(400,"手机号不存在，请先注册");
        }
    }

    /**
     * 手机验证码登录
     *
     * @param vo
     * @return
     */
    @Override
    public ResponseDTO loginAndCode(LoginVo vo) {
        System.out.println("*******loginAndCode*******" + vo);
        Users Phone = userMapper.selectByPhone(vo.getPhoneNumber());
        if (Phone != null) {
//            Users loginandcode = userMapper.loginAndcode(vo.getPhoneNumber());
//            if (loginandcode != null) {
                ClaimsBuilder claims = Jwts.claims();
                claims.add("PhoneNumber", Phone.getPhoneNumber());
                String token = JWTUtils.getToken(claims.build());
                System.out.println("生成的token是:" + token);
                Phone.setPassWord("");
                Phone.setSalt("");
                redisTemplate.opsForValue().set(token, Phone);
                redisTemplate.expire("token", 1000, TimeUnit.SECONDS);
                Phone.setToken(token);
                System.out.println(Phone);
                return ResponseDTO.success("登录成功", Phone);
//            }
//            return ResponseDTO.error("登录失败");
        } else {
            UUID uuid = UUID.randomUUID();
            String substring = uuid.toString().substring(5, 10);
            System.out.println("sub:"+substring);
            userMapper.registerPhone(vo.getPhoneNumber(), substring);
            return ResponseDTO.error("手机号未注册，现已注册");
        }
    }

    /**
     * 邮箱和密码登录
     *
     * @param vo
     * @return
     */
    @Override
    public ResponseDTO emailAndpwd(LoginVo vo) {
        Users email = userMapper.selectByemail(vo.getEmail());
        if (email != null) {
            Users emaillogin = userMapper.emailAndpwd(vo.getEmail(), vo.getPassWord());
            if (emaillogin != null) {
                ClaimsBuilder claims = Jwts.claims();
                claims.add("Email", email.getEmail());
                String token = JWTUtils.getToken(claims.build());
                System.out.println("生成的token是:" + token);
                redisTemplate.opsForValue().set(token, email);
                redisTemplate.expire("token", 1000, TimeUnit.SECONDS);
                email.setToken(token);
                return ResponseDTO.success("登录成功", emaillogin);
            }
            return ResponseDTO.error("登录失败");
        } else {
            return ResponseDTO.error("邮箱不存在，请先绑定");
        }
    }

    /**
     * 邮箱和验证码登录
     *
     * @param vo
     * @return
     */
    @Override
    public RestBean<Users> mailAndcode(LoginVo vo) {
        Users email = userMapper.selectByemail(vo.getEmail());
        if (email != null) {
            Users emaillogin = userMapper.mailAndcode(vo.getEmail());
            if (emaillogin != null) {
                ClaimsBuilder claims = Jwts.claims();
                claims.add("Email", email.getEmail());
                String token = JWTUtils.getToken(claims.build());
                System.out.println("生成的token是:" + token);
                redisTemplate.opsForValue().set(token, email);
                redisTemplate.expire("token", 1000, TimeUnit.SECONDS);
                email.setToken(token);
                return RestBean.success("登录成功", emaillogin);
            }
            return RestBean.failure(400,"登录失败");
        } else {
            return RestBean.failure(400,"邮箱不存在，请先绑定");
        }
    }

    /**
     * 通过手机更改密码
     *
     * @param vo
     * @return
     */
    @Override
    public ResponseDTO Changepassword(LoginVo vo) {
        System.out.println("******" + vo);
        Users Phone = userMapper.selectByPhone(vo.getPhoneNumber());
        if (Phone != null) {
            int changepassword = userMapper.Changepassword(vo.getPhoneNumber(), vo.getPassWord());
            if (changepassword > 0) {
                return ResponseDTO.success("密码修改成功");
            } else {
                return ResponseDTO.success("密码修改失败");
            }
        } else {
            return ResponseDTO.error("手机号码不存在，请先注册");
        }
    }

    /**
     * 绑定邮箱
     *
     * @param vo
     * @return
     */
    @Override
    public ResponseDTO bindemail(LoginVo vo) {
        System.out.println("*********" + vo);
        Users email = userMapper.selectByemail(vo.getEmail());
        if (email != null) {
            return ResponseDTO.error("该邮箱被绑定请换个邮箱");
        } else {
            userMapper.bindemail(vo.getPhoneNumber(), vo.getEmail());
            return ResponseDTO.success("邮箱被绑定成功");
        }
    }

    @Override
    public ResponseDTO ChangeInformation(Users users) {
        int i = userMapper.ChangeInformation(users);
        if (i > 0) {
            return ResponseDTO.success("信息修改成功");
        }
        return ResponseDTO.error("信息修改失败");
    }

    /**
     * 注销用户
     * @param vo
     * @return
     */
    @Override
    public ResponseDTO LogoutUser(LoginVo vo) {
        userMapper.LogoutUser(vo.getId());
        return ResponseDTO.success("用户注销成功");
    }
    //根据用户id返回用户信息
    @Override
    public RestBean<Users> FindUser(String id) {
        Long _id;
        try {
            _id = Long.parseLong(id);
        }catch (NumberFormatException e){
            return RestBean.failure(400,"参数错误");
        }
        Users findUser = userMapper.FindUser(_id);
        if (findUser != null){
            return RestBean.success("用户查找成功",findUser);
        }
        return RestBean.failure(400,"用户查找失败");
    }

    @Override
    public ResponseDTO isBlocked(LoginVo vo) {
        Users userisBlocked = userMapper.UserisBlocked( vo.getId(),vo.getBlockedUserId());
        if (userisBlocked !=null){
            return ResponseDTO.success("双向用户黑名单查找成功",userisBlocked);
        }
        return ResponseDTO.error("双向用户黑名单查找失败");
    }

    @Override
    public ResponseDTO addBlock(LoginVo vo) {
        int i = userMapper.isBlocked(vo.getId(),vo.getBlockedUserId());
        if (i > 0) {
            return ResponseDTO.success("用户拉黑成功");
        }
        return ResponseDTO.error("用户拉黑失败");
    }

    @Override
    public ResponseDTO UserBalance(Long id) {
        System.out.println("***Impl****"+id);
        int userBalance = userMapper.UserBalance(id);
        if (userBalance > 0) {
            return ResponseDTO.success("用户余额查询成功",userBalance);
        }
        return ResponseDTO.error("用户余额查询失败");
    }

    @Override
    public RestBean authentication(Long IdCard, Long id) {
        int authentication = userMapper.authentication(IdCard, id);
        int i = userMapper.authenticationStatus(id);

        if (authentication >0&&i>0){
            return RestBean.success("认证成功");
        }
        return RestBean.failure(400,"认证失败");
    }
    // 注销用户
    @Override
    public RestBean quitUser(String id) {
        Long _id;
        try{
            _id = Long.parseLong(id);
        }catch (NumberFormatException e){
            return RestBean.failure(400,"参数错误");
        }
        // 查询用户是否存在
        Users user = userMapper.FindUser(_id);
        if (user == null) {
            return RestBean.failure(400, "用户不存在");
        }
        // 获取用户token
        String token = user.getToken();
        if (token == null || token.isEmpty()) {
            return RestBean.failure(400, "用户未登录或已注销");
        }
        // 从Redis中删除token
        redisTemplate.delete(token);
        // 清除用户对象中的token
        user.setToken(null);
        return RestBean.success("注销成功");
    }
}









